<template>
  <a-drawer
    :width="420"
    :visible="showDrawer"
    @ok="handleSubmit"
    @cancel="handleCancel"
    unmountOnClose
  >
    <template #title>{{ getTitle }}</template>
    <div class="drawer-box">
      <a-form ref="formRef" :model="formData" auto-label-width>
        <a-form-item
          field="name"
          :label="t('searchTable.columns.name_role')"
          validate-trigger="input"
          disabled
          style="margin-bottom: 15px"
        >
          <a-input
            v-model="formData.name"
            :placeholder="t('modal.please.write.name_role')"
            allow-clear
          />
        </a-form-item>
        <a-form-item
          field="remark"
          :label="t('searchTable.columns.remark')"
          validate-trigger="input"
          style="margin-bottom: 15px"
        >
          <a-input
            disabled
            v-model="formData.remark"
            :placeholder="t('modal.please.write.remark')"
            allow-clear
          />
        </a-form-item>
        <a-form-item
          field="menu"
          :label="$t('searchTable.columns.addDrawer.permissions.assignment')"
          style="margin-bottom: 5px"
        >
          <a-row class="wrapper">
            <a-col :span="24">
              <a-tabs default-active-key="1" type="rounded">
                <a-tab-pane
                  key="1"
                  :title="$t('searchTable.columns.addDrawer.menu.settings')"
                >
                  <a-spin :loading="loading" style="width: 100%">
                    <div class="rule_data">
                      <div class="haeder">
                        <a-checkbox
                          v-if="!isRules"
                          v-model="IsCheckedRules"
                          @change="toggleCheckedRules"
                          style="margin-right: 15px"
                        >
                          {{
                            IsCheckedRules
                              ? t('modal.cancel')
                              : t('modal.selectAll')
                          }}
                        </a-checkbox>
                        <a-checkbox
                          v-model="onExpandedRules"
                          @change="toggleExpandedRules"
                          >{{
                            onExpandedRules
                              ? t('modal.collapse')
                              : t('modal.expand')
                          }}
                        </a-checkbox>
                      </div>
                      <div class="treebox">
                        <a-tree
                          :show-line="true"
                          :checkable="!isRules"
                          v-model:checked-keys="formData.menu"
                          :fieldNames="{
                            key: 'id',
                            title: 'locale',
                            children: 'children',
                          }"
                          ref="ruleTreeRef"
                          @check="onCheckRules"
                          :data="menutreeData"
                        />
                      </div>
                    </div>
                  </a-spin>
                </a-tab-pane>
                <a-tab-pane
                  key="2"
                  :title="$t('searchTable.columns.addDrawer.api.settings')"
                >
                  <a-spin :loading="loading" style="width: 100%">
                    <div class="rule_data">
                      <div class="haeder">
                        <a-checkbox
                          v-if="!isApis"
                          v-model="IsCheckedApis"
                          @change="toggleCheckedApis"
                          style="margin-right: 15px"
                        >
                          {{
                            IsCheckedApis
                              ? t('modal.cancel')
                              : t('modal.selectAll')
                          }}
                        </a-checkbox>
                        <a-checkbox
                          v-model="onExpandedApis"
                          @change="toggleExpandedApis"
                          >{{
                            onExpandedApis
                              ? t('modal.collapse')
                              : t('modal.expand')
                          }}
                        </a-checkbox>
                      </div>
                      <div class="treebox">
                        <a-tree
                          :show-line="true"
                          :checkable="!isApis"
                          v-model:checked-keys="formData.apis"
                          :fieldNames="{
                            key: 'id',
                            title: 'locale',
                            children: 'children',
                          }"
                          ref="apisTreeRef"
                          @check="onCheckApis"
                          :data="apistreeData"
                        />
                      </div>
                    </div>
                  </a-spin>
                </a-tab-pane>
              </a-tabs>
            </a-col>
          </a-row>
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, computed, unref } from 'vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import useLoading from '@/hooks/loading';
  import { cloneDeep } from 'lodash-es';
  //api
  import { Icon } from '@/components/Icon';
  import { Message } from '@arco-design/web-vue';
  import { DataTreeItemRule, getAllRule } from '@/api/systemManage/rule';
  import {
    getAllRuleIds,
    getApi,
    getRule,
    updateApi,
    updateRule,
  } from '@/api/systemManage/role';
  import { useI18n } from 'vue-i18n';
  import { DataTreeItemApis, getAllApi } from '@/api/systemManage/api';

  export default defineComponent({
    name: 'AddDrawer',
    components: { Icon },
    emits: ['success'],
    setup(_, { emit }) {
      const showDrawer = ref(false);
      const isUpdate = ref(false);
      const parntList = ref<DataTreeItemRule[]>([]);
      const { t } = useI18n();
      //表单
      const formRef = ref<FormInstance>();
      //表单字段
      const basedata = {
        id: 0,
        name: '',
        remark: '',
        menu: [], //选择的id，用于编辑赋值
        apis: [], //规则ID 所拥有的权限包扣父级
        weigh: 1,
        data_access: 0,
      };
      const formData = ref(basedata);
      //菜单权限
      const isRules = ref(false);
      const IsCheckedRules = ref(false);
      const onExpandedRules = ref(false);
      const ruleTreeRef = ref();
      const menutreeData = ref<DataTreeItemRule[]>([]);
      const isApis = ref(false);
      const IsCheckedApis = ref(false);
      const onExpandedApis = ref(false);
      const apisTreeRef = ref();
      const apistreeData = ref<DataTreeItemApis[]>([]);

      function mapRuleToTreeItem(list: any[]): DataTreeItemRule[] {
        return list.map((item) => ({
          id: item.id,
          title: item.title,
          locale: t(item.locale),
          children: item.children ? mapRuleToTreeItem(item.children) : [],
        }));
      }

      function mapApisToTreeItem(list: any[]): DataTreeItemApis[] {
        if (!Array.isArray(list)) return [];

        // 先按 api_group 分组
        const groupMap: Record<string, any[]> = {};
        list.forEach((item) => {
          const group = item.api_group;
          if (!groupMap[group]) {
            groupMap[group] = [];
          }
          groupMap[group].push(item);
        });

        // 转换成 Tree 结构
        const treeData: DataTreeItemApis[] = Object.keys(groupMap).map(
          (group) => ({
            id: group, // 分组名当 id
            title: group,
            locale: group,
            children: groupMap[group].map((api) => ({
              id: api.id,
              title: `${api.method} ${api.path}`,
              locale: `${api.desc || api.title || ''} - ${api.method}`,
              children: [],
            })),
          })
        );

        return treeData;
      }

      //打开弹框
      const openDrawer = async (item: any) => {
        isUpdate.value = !!item?.isUpdate;
        showDrawer.value = true;
        formRef.value?.resetFields();
        // 1、打开弹窗请求所有的rule，api
        //获取所有菜单
        const id = unref(isUpdate) ? item.record.id : 0;
        // 获取有权限的菜单
        const resultDataRule = await getRule({ id: id });
        // 获取有权限的api
        const resultDataApi = await getApi({ id: id });

        // 2、获取当前角色所有的rule，api权限
        // 3、选中已经拥有的权限
        if (unref(isUpdate)) {
          formData.value = cloneDeep(item.record);
          if (resultDataRule) {
            formData.value.menu = cloneDeep(getAllRuleIds(resultDataRule.list));
          }
          if (resultDataApi) {
            formData.value.apis = cloneDeep(
              resultDataApi.list.map((item) => item.id)
            );
          }
        } else {
          formData.value.menu = [];
          formData.value.apis = [];
        }

        const resultDataAllRule = await getAllRule({ state: 2 });
        menutreeData.value = cloneDeep(
          mapRuleToTreeItem(resultDataAllRule.list)
        );
        const resultDataAllApis = await getAllApi({ state: 2 });
        apistreeData.value = cloneDeep(
          mapApisToTreeItem(resultDataAllApis.list)
        );
        nextTick(() => {
          onExpandedRules.value = true;
          ruleTreeRef.value.expandAll(onExpandedRules.value);

          onExpandedApis.value = true;
          apisTreeRef.value.expandAll(onExpandedApis.value);
        });
      };
      const getTitle = computed(() =>
        !unref(isUpdate)
          ? ''
          : t('searchTable.columns.addDrawer.character.permissions')
      );
      //点击确认
      const { loading, setLoading } = useLoading();
      const handleSubmit = async () => {
        try {
          const res = await formRef.value?.validate();
          if (!res) {
            setLoading(true);
            Message.loading({
              content: t('searchTable.message.loading.updating'),
              id: 'upStatus',
            });
            const info = unref(formData);
            const paramsRule = {
              id: info.id,
              menu_ids: info.menu,
            };
            const paramsApis = {
              id: info.id,
              api_ids: info.apis,
            };

            await updateRule(paramsRule);
            // menus存储
            await updateApi(paramsApis);
            // apis存储

            Message.success({
              content: t('searchTable.message.loading.update.successful'),
              id: 'upStatus',
            });
            emit('success');
            showDrawer.value = false;
            setLoading(false);
          }
        } catch (error) {
          setLoading(false);
          Message.clear('top');
        }
      };
      const handleCancel = () => {
        showDrawer.value = false;
      };
      //权限菜单
      //全选
      const toggleCheckedRules = (value: any) => {
        ruleTreeRef.value.checkAll(value);
      };
      //展开
      const toggleExpandedRules = (value: any) => {
        ruleTreeRef.value.expandAll(value);
      };
      //选中
      const onCheckRules = (newCheckedKeys: any, event: any) => {
        formData.value.menu = newCheckedKeys;
      };
      //权限菜单
      //全选
      const toggleCheckedApis = (value: any) => {
        apisTreeRef.value.checkAll(value);
      };
      //展开
      const toggleExpandedApis = (value: any) => {
        apisTreeRef.value.expandAll(value);
      };
      //选中
      const onCheckApis = (newCheckedKeys: any, event: any) => {
        formData.value.apis = newCheckedKeys;
      };
      return {
        t,
        showDrawer,
        handleCancel,
        openDrawer,
        getTitle,
        handleSubmit,
        formRef,
        loading,
        formData,
        parntList,
        menutreeData,
        onCheckRules,
        toggleCheckedRules,
        toggleExpandedRules,
        ruleTreeRef,
        onExpandedRules,
        IsCheckedRules,
        isRules, //是否是超级权限
        apistreeData,
        onCheckApis,
        toggleCheckedApis,
        toggleExpandedApis,
        apisTreeRef,
        onExpandedApis,
        IsCheckedApis,
        isApis, //是否是超级权限
      };
    },
  });
</script>
<style lang="less" scoped>
  .drawer-box {
    .rule_data {
      width: 100%;

      .haeder {
        border-bottom: var(--color-neutral-4) solid 1px;
      }
    }
  }
</style>
